package com.example.ali.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.example.ali.domain.dto.MyDetectionDto;
import com.example.ali.domain.vo.MyOcrResult;
import com.example.ali.service.IAliOcrService;
import com.example.ali.service.IMyBuildDtoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 〈〉
 *
 * @author hero
 * @create 2024/5/29
 * @since 1.0.0
 */
@Service
public class AliOcrServiceImpl implements IAliOcrService {

    @Autowired
    com.aliyun.ocr_api20210707.Client aliOcrClient;

    /**
     * 获取OCR识别结果
     * @param fileInputStream
     * @param startRow
     * @return
     */
    @Override
    public List<Map<String, String>> getValueMap(InputStream fileInputStream, Integer startRow) {
        String jsonString = getOcrResult(fileInputStream);
        JSONObject resJson = JSONObject.parseObject(jsonString);
        JSONObject body = resJson.getJSONObject("body");
        JSONObject data = body.getJSONObject("data");
        JSONArray tableInfos = data.getJSONArray("prism_tablesInfo");
        JSONArray cellArray = tableInfos.getJSONObject(0).getJSONArray("cellInfos");
        List<MyOcrResult> myOcrResults = JSONArray.parseArray(Common.toJSONString(cellArray), MyOcrResult.class);
        Integer maxRowIndex = tableInfos.getJSONObject(0).getInteger("yCellSize");
        Integer maxColumnIndex =  tableInfos.getJSONObject(0).getInteger("xCellSize");
        List<Map<String, String>> mapList = getValueMapFromOcrResult(myOcrResults, maxRowIndex, startRow);
        return mapList;
    }

    /**
     * 获取OCR识别结果
     * @param fileInputStream
     * @return
     */
    private String getOcrResult(InputStream fileInputStream) {
        String jsonString = "";
        com.aliyun.ocr_api20210707.models.RecognizeHandwritingRequest recognizeHandwritingRequest = new com.aliyun.ocr_api20210707.models.RecognizeHandwritingRequest()
                .setBody(fileInputStream)
                .setNeedRotate(true)
                .setOutputTable(true)
                .setNeedSortPage(true)
                .setParagraph(true);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            com.aliyun.ocr_api20210707.models.RecognizeHandwritingResponse resp = aliOcrClient.recognizeHandwritingWithOptions(recognizeHandwritingRequest, runtime);
            jsonString = Common.toJSONString(resp);

            System.out.println("获取到的列表信息：\n"+jsonString);
            return jsonString;
        } catch (Exception _error) {
            System.out.println(_error);
        }
        return jsonString;
    }

    /**
     * 获取OCR识别结果，生成Map列表
     *
     * @param ocrResultList
     * @param maxRow
     * @param startRow
     * @return
     */
    private List<Map<String, String>> getValueMapFromOcrResult(List<MyOcrResult> ocrResultList, Integer maxRow, Integer startRow) {
        List<Map<String, String>> valueMapList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(ocrResultList)) {
            // 构建结果
            for (int tmpRow = startRow; tmpRow < (maxRow >= 1 ? maxRow - 1 : 0); tmpRow++) {
                Integer tt = tmpRow;
                List<MyOcrResult> resultList = ocrResultList.stream()
                        .filter(x -> tt.equals(x.getYsc()))
                        .collect(Collectors.toList());
                Map<String, String> valueMap = new HashMap<>();
                resultList.forEach(x -> valueMap.put(x.getXsc().toString(), x.getWord()));
                valueMapList.add(valueMap);
            }
        }
        return valueMapList;
    }


    /**
     * @param filePath "/Users/hero/Downloads/ocr/ocr3.png"
     * @return
     * @throws Exception
     */
    // @Override
    private List<MyDetectionDto> getOcr(String filePath) throws Exception {
        List<MyDetectionDto> detectionDtoList=new ArrayList<>();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream = com.aliyun.darabonba.stream.Client.readFromFilePath(filePath);
        com.aliyun.ocr_api20210707.models.RecognizeHandwritingRequest recognizeHandwritingRequest = new com.aliyun.ocr_api20210707.models.RecognizeHandwritingRequest()
                .setBody(bodyStream)
                .setNeedRotate(true)
                .setOutputTable(true)
                .setNeedSortPage(true)
                .setParagraph(true);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            com.aliyun.ocr_api20210707.models.RecognizeHandwritingResponse resp = aliOcrClient.recognizeHandwritingWithOptions(recognizeHandwritingRequest, runtime);
            JSONObject resJson = JSONObject.parseObject(com.aliyun.teautil.Common.toJSONString(resp));
            JSONObject body = resJson.getJSONObject("body");
            JSONObject data = body.getJSONObject("data");
            JSONArray tableInfos = data.getJSONArray("prism_tablesInfo");
            JSONArray cellArray = tableInfos.getJSONObject(0).getJSONArray("cellInfos");
            List<MyOcrResult> myOcrResults = JSONArray.parseArray(Common.toJSONString(cellArray), MyOcrResult.class);
            Integer maxRowIndex = tableInfos.getJSONObject(0).getInteger("yCellSize");
            Integer maxColumnIndex =  tableInfos.getJSONObject(0).getInteger("xCellSize");
            //获取数据信息
            List<Map<String, String>> mapList = getValueMapFromOcrResult(myOcrResults, maxRowIndex, 3);
            //构建实体类列表
            // detectionDtoList = myBuildDtoService.buildDto(mapList);
            System.out.println("获取到的列表信息：\n"+detectionDtoList.toString());

        } catch (Exception error) {
            System.out.println("获取OCR识别结果失败：\n"+error);
        }
        return detectionDtoList;
    }

    // @Override
    private List<MyDetectionDto> postOcr(InputStream fileInputStream) throws Exception {
        List<MyDetectionDto> detectionDtoList=new ArrayList<>();
        com.aliyun.ocr_api20210707.models.RecognizeHandwritingRequest recognizeHandwritingRequest = new com.aliyun.ocr_api20210707.models.RecognizeHandwritingRequest()
                .setBody(fileInputStream)
                .setNeedRotate(true)
                .setOutputTable(true)
                .setNeedSortPage(true)
                .setParagraph(true);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            com.aliyun.ocr_api20210707.models.RecognizeHandwritingResponse resp = aliOcrClient.recognizeHandwritingWithOptions(recognizeHandwritingRequest, runtime);
            JSONObject resJson = JSONObject.parseObject(com.aliyun.teautil.Common.toJSONString(resp));
            JSONObject body = resJson.getJSONObject("body");
            JSONObject data = body.getJSONObject("data");
            JSONArray tableInfos = data.getJSONArray("prism_tablesInfo");
            JSONArray cellArray = tableInfos.getJSONObject(0).getJSONArray("cellInfos");
            List<MyOcrResult> myOcrResults = JSONArray.parseArray(Common.toJSONString(cellArray), MyOcrResult.class);
            Integer maxRowIndex = tableInfos.getJSONObject(0).getInteger("yCellSize");
            Integer maxColumnIndex =  tableInfos.getJSONObject(0).getInteger("xCellSize");
            //获取数据信息
            List<Map<String, String>> mapList = getValueMapFromOcrResult(myOcrResults, maxRowIndex, 3);
            //构建实体类列表
            // detectionDtoList = myBuildDtoService.buildDto(mapList);
            System.out.println("获取到的列表信息：\n"+detectionDtoList.toString());

        } catch (Exception _error) {
            System.out.println(_error);
        }
        return detectionDtoList;
    }




}
